<template>
  <div class="w-full">
    <router-view></router-view>
  </div>
  <div v-if="data.fing === 0" class="h-1/2">
    <!-- 头部 -->
    <div class="h-12 bg-aqua">
      <!-- 搜索框部分 -->
      <div>
        <div class="flex justify-center items-center">
          <el-input
            v-model="data.bookname"
            placeholder="搜索商品"
			style="width: 250px;"
            clearable
          />
          <el-button @click="search" :icon="Search" circle />
        </div>
      </div>
      <!-- 级联选择器部分 -->
      <div class="h-5 p-1 flex justify-center">
        <el-cascader :options="options">
          <template #default="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </div>
    </div>
    <!-- 轮播图部分 -->
    <div class="h-100vh w-full" >
		<el-carousel :interval="3000" arrow="always">
        <el-carousel-item v-for="item in data.cimg" :key="item.id">
			<img :src="`/api/public/findAllimg/${item.id}`" style="width: 100%; height:100%;" />
                  </el-carousel-item>
      </el-carousel>	
      
    </div>
    <!-- 商品展示部分 -->
    <div class="container mx-auto p-4 bg-green-400">
      <h1 class="text-2xl font-bold mb-4">商品展示 <hr class="border-blue-500" /></h1>
      <el-row :gutter="20">
        <el-col :span="6" v-for="x in data.goods" :key="x.id">
          <el-card class="shadow-md transition-transform hover:scale-105">
            <template #header>
              <div class="w-10vw h-10vh">
                <img :src="`/api/public/findgoodsimg/${x.gid}`" style="width: 100%;height: ;" />
              </div>
            </template>
            <div class="p-4">
              <p class="text-sm mb-2 image-zoom">{{ x.bookname }}</p>
              <div class="flex justify-between items-center">
                <h3 class="text-red-500">原价: {{ x.price }}￥</h3>
                <h3 class="text-red-500">会员价: {{ x.vip }}￥</h3>
                <p class="text-gray-500 text-sm">{{ x.reviews }} 人评价</p>
                <el-button @click="addCart(x)" type="warning" :icon="Star" circle />
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- 尾部部分 -->
    <div class="flex justify-center text-center">
      <div >
        <p>正品商品</p>
        <img src="../assets/品.png" class="mx-auto" />
      </div>
      <div >
        <p>发货迅速</p>
        <img src="../assets/icon_ffs.png" class="mx-auto" />
      </div>
      <div >
        <p>7天无理由退货</p>
        <img src="../assets/tianwuraotuihuan.png" class="mx-auto" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { $get, $postx, $postf } from "../ajax/index.js"
import myalert from "../utils/myalert.js"
import alert from "../components/Alert.vue"
import store from "../store/index.js"
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const formData = new FormData()
const data = reactive({
  goods: [], // 商品
  user: {}, // 用户
  cimg: [], // 轮播图
  fing: 0, // 0是显示、1是隐藏
  bookname: '', // 搜索商品
  bood: {},
})

// 类型选项
const options = ref<any[]>([])

// 统一的错误处理函数
const handleError = (error: any, message: string) => {
  console.error(`${message}:`, error)
}

// 获取轮播图数据
const fetchCarouselImages = async () => {
  try {
    const resp = await $get("/api/public/imgfindAll")
    data.cimg = resp.data.data
  } catch (error) {
    handleError(error, '获取轮播图数据失败')
  }
}

// 获取商品数据
const fetchGoods = async () => {
  try {
    const resp = await $get("/api/public/goodsfind")
    data.goods = resp.data.data
  } catch (error) {
    handleError(error, '获取商品数据失败')
  }
}

// 获取类型数据
const fetchTypes = async () => {
  try {
    const resp = await $get("/api/public/findtppe")
	console.log(resp.data.data)
    const data = resp.data.data
    const mappedData: any[] = []
    const idToItemMap: { [key: string]: any } = {}

    // 先将所有数据根据 id 存储到对象中，方便查找
    data.forEach((item) => {
      idToItemMap[item.tid] = {
        value: item.tid.toString(),
        label: item.tname,
        children:item.children,
      }
    })

    data.forEach((item) => {
      if (item.pid === 0) {
        mappedData.push(idToItemMap[item.tid])
      } else {
        const parent = idToItemMap[item.pid]
        if (parent) {
          parent.children.push(idToItemMap[item.tid])
        }
      }
    })

    options.value = mappedData
  } catch (error) {
    handleError(error, '获取类型数据失败')
  }
}

onMounted(async () => {
  await fetchCarouselImages()
  await fetchGoods()
  await fetchTypes()
})

const router = useRouter()
// 搜索商品并跳转到商品页面
const search = () => {
  data.fing = 1
  router.push({
    path: "/seller/good",
    query: {
      bookname: data.bookname,
    },
  })
}
// 跳转到购物页面
const goAdd = (bookid: number) => {
  data.fing = 1
  router.push({
    path: "/seller/shopping",
    query: {
      id: bookid,
    },
  })
}
// 添加购物车
const addCart = (x: any) => {
  const fd = new FormData()
  fd.append("id", "0")
  fd.append("uid", store.state.user.uid)
  fd.append("num", "1")
  fd.append("goods.bookid", x.bookid)
  if (store.state.user.vip === 0) fd.append("price", x.price)
  if (store.state.user.vip === 1) fd.append("price", x.vip)
  $postf("/api/seller/cart/addcart", fd)
  ElMessage({
    message: "添加购物车成功!!!",
    type: 'success',
  })
}
// 轮播图函数
const Carousel = () => {
  // 可以在这里添加轮播图的逻辑
}
</script>

<style scoped>
.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.image-zoom {
  transition: transform 0.3s ease;
}

.image-zoom:hover {
  transform: scale(1.1);
}
</style>    